﻿#include "widget_gpio_input.h"
#include "arrow_item.h"
#include "mhelper.h"
#include "ui_widget_gpio_input.h"

#include <QButtonGroup>
#include <QCheckBox>
#include <QGraphicsItem>
#include <QGraphicsProxyWidget>
#include <QHBoxLayout>
#include <QMetaObject>
#include <QStackedWidget>
#include <com_manager.h>


#pragma execution_character_set("utf-8")

Widget_GPIO_Input::Widget_GPIO_Input(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget_GPIO_Input)
{
    ui->setupUi(this);

    ui->label_gpio->hide();
    ui->pushButton_read->hide();

    scene = new QGraphicsScene();
    view = new QGraphicsView(scene);

    QHBoxLayout *layout = new QHBoxLayout;
    //dw new5
    // view = new QGraphicsView(scene);

    view->centerOn(0, 0);

    //view = new MyFasterGraphicView(scene);
    view->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);

    layout->addWidget(view);
    layout->setMargin(0);

    //QWidget *widget = new QWidget;
    ui->widget->setLayout(layout);

    // this->setCentralWidget(view);
    scene->setSceneRect(0,0,ui->widget->width(),ui->widget->height());
    //  scene->setRect(view->rect());
    view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    view->setRenderHint(QPainter::Antialiasing);

    // pen = new QPen();
    // scene->setPen(pen);
    // brush = new QBrush(*(new QColor("white")),Qt::NoBrush);
    // scene->setBrush(brush);

     if ( GpioSetting::gpio.count() > 0)
     {
        if (com_manager::instance()->comList.count()>0)
        initChart(com_manager::instance()->comList[0], 0 );

     }
}

Widget_GPIO_Input::~Widget_GPIO_Input()
{
    delete ui;
}

void Widget_GPIO_Input::initChart(QString com, int index)
{
    com_name = com;
    gpio_id = index;

    GPIO* gpio = GpioSetting::gpio[com_name][index];
    if(gpio!=NULL )
        _gpio = *gpio;

    _gpio.mode_input = 1;

    ui->label_gpio->setText("寄存器值："+gpio->toString());
    ui->label_new_gpio->setText( _gpio.toString());

    scene->clear() ;

    QPen pen_enable (Qt::black , 3, Qt::SolidLine);
    QPen pen_disable(Qt::gray, 2, Qt::DashLine);


    QPen pen_pin(pen_enable);
    QPen pen_user(pen_disable);

    if ( !_gpio.on)
    {
        pen_pin = QPen(pen_disable);
        pen_user  = QPen(pen_enable);
    }

    QLabel * labelBus= new QLabel("BUS") ;
    labelBus->setAlignment(Qt::AlignHCenter|Qt::AlignCenter);
    labelBus->setFrameShape( QFrame::Box );
    scene->addWidget(labelBus);
           labelBus->setGeometry( QRect(120, 100-60, 280, 60 )) ;


    QPolygon polygon;
    polygon.append(QPoint(250,160-60) );
    polygon.append(QPoint(250,200-60) );
    polygon.append(QPoint(160,200-60) );
    polygon.append(QPoint(160,260-60) );

    QPainterPath path  ;
    path.addPolygon(polygon);
    item_path = scene->addPath(path, pen_pin) ;
    item_path->setPen(pen_pin);

    arrow_1= new ArrowItem(QPoint(250,200-60), QPoint(250,160-60));
    arrow_1->setPen(pen_enable);
    scene->addItem(arrow_1);

    btnFlip     = new QCheckBox("翻转") ;
    btnFlip->setStyleSheet(" QCheckBox{border: 1px solid #b1b1b1; }");

    btnFlip->setEnabled(_gpio.on);
    QGraphicsProxyWidget * pFlipWidget=scene->addWidget(btnFlip);
    // pFlipWidget->setPos(120,260);
    pFlipWidget->setGeometry(QRect(120,240-40, 80, 40));
    pFlipWidget->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦
    QMetaObject::Connection c=   connect(btnFlip, &QPushButton::clicked, [=] {
        //mHelper::ShowMessageBoxInfoX("翻转");
        _gpio.flip = btnFlip->isChecked();
        updateChart( );
    });


   // line_1 = scene->addLine( 160,300-60, 160, 360-60, pen_pin);
   // line_1->setPen(pen_pin);
    // scene->addRect(QRect(120,360, 80, 40 ));
    // scene->add_Text("引脚" , QPoint(120, 360) ) ;
    arrow_2 = new ArrowItem(QPoint( 160, 360-60), QPoint(160, 280-40));
    arrow_2->setPen(pen_pin);
    scene->addItem(arrow_2);


    btnPin  = new QPushButton("引脚") ;
    btnPin->setCheckable(true);
    btnPin->setChecked(_gpio.on);
    QGraphicsProxyWidget * pWidgetPin=scene->addWidget(btnPin);
    pWidgetPin->setPos(160,360-60);
    pWidgetPin->setGeometry(QRect(120,360-60, 80, 40));
    pWidgetPin->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦
    QMetaObject::Connection c1= connect(btnPin, &QPushButton::clicked, [=] {
        //mHelper::ShowMessageBoxInfoX("引脚");
        _gpio.on = 1;
        updateChart( );
    });

    QLabel * label_pin = new QLabel(QString("GPIO pin: %1").arg(gpio_id));
    QGraphicsProxyWidget * plabel_pin=scene->addWidget(label_pin);
    plabel_pin->setPos(120,360-60+40 );



    //////////////////////////
    /// \brief user
    /////
    QPolygon polygon_;
  //  polygon_.append(QPoint(250,160-60) );
    polygon_.append(QPoint(250,200-60) );
    polygon_.append(QPoint(340,200-60) );
    polygon_.append(QPoint(340,260-60) );

#if    (QT_VERSION <= QT_VERSION_CHECK(5,13,0))
    path = QPainterPath();
#else
    path.clear() ;
#endif
    path.addPolygon(polygon_);
    user_path=  scene->addPath(path,pen_user) ;
    user_path->setPen(pen_user);

   // line_3= scene->addLine( 340,260-60, 340, 360-60, pen_user);
  //  line_3->setPen(pen_user);


    //默认值
    QLabel * label = new QLabel("默认值");
    QGraphicsProxyWidget * plabel=scene->addWidget(label);
    plabel->setPos(400,260-60+4 );

    user_default = new QComboBox;
    user_default->addItem("0");
    user_default->addItem("1");
    QGraphicsProxyWidget * pCombo=scene->addWidget(user_default);
    pCombo->setPos(300,260-60);
    pCombo->setGeometry(QRect(300,260-60, 80, 32));
    connect(user_default, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [=](int index){
        _gpio.level = index;
        updateChart();
    });

    arrow_3 = new ArrowItem(QPoint( 340, 360-60), QPoint(340, 300-60-8));
    arrow_3->setPen(pen_user);
    scene->addItem(arrow_3);
    arrow_3->setZValue(-1000);

    btnUser    = new QPushButton("用户") ;
    btnUser->setCheckable(true);

    btnUser->setChecked(!_gpio.on);

    QGraphicsProxyWidget * pWidgetUser=scene->addWidget(btnUser);
    pWidgetUser->setPos(300,360-60);
    pWidgetUser->setGeometry(QRect(300,360-60, 80, 40));
    pWidgetUser->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); //通过QGraphicsProxyWidget指针设置其可选、可移动、可聚焦
    QMetaObject::Connection c2=  connect(btnUser, &QPushButton::clicked, [=] {
        // mHelper::ShowMessageBoxInfoX("用户");
        _gpio.on = 0;
        updateChart( );
    });


    QButtonGroup * group = new QButtonGroup;
    group->addButton(btnPin);
    group->addButton(btnUser);

    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        if (   rs232 ->myCom && rs232 ->myCom ->isOpen())
        {
            ui->pushButton_read->setEnabled(true);
            ui->pushButton_save->setEnabled(true);
        }
        else
        {
            ui->pushButton_read->setEnabled(false);
            ui->pushButton_save->setEnabled(false);
        }
    }
}

void Widget_GPIO_Input::updateChart( )
{
    QPen pen_enable (Qt::black , 3, Qt::SolidLine);
    QPen pen_disable(Qt::gray, 2, Qt::DashLine);

    QPen pen_pin(pen_enable);
    QPen pen_user(pen_disable);
    if ( !_gpio.on)
    {
        pen_pin = QPen(pen_disable);
        pen_user  = QPen(pen_enable);
    }


    ui->label_new_gpio->setText(_gpio.toString());

    user_default->setCurrentIndex(_gpio.level);
    btnFlip->setEnabled(_gpio.on);

    item_path->setPen(pen_pin);
    arrow_1->setPen(pen_enable);
    arrow_2->setPen(pen_pin);
   // line_1->setPen(pen_pin);

    user_path->setPen(pen_user);
    arrow_3->setPen(pen_user);
  //  line_3->setPen(pen_user);


    btnFlip->setEnabled(_gpio.on);
    btnFlip->setChecked( _gpio.flip);
    btnPin->setChecked(_gpio.on);
    btnUser->setChecked(!_gpio.on);
    

    //////////////////////////////
    GPIO* gpio = GpioSetting::gpio[com_name][gpio_id];
    ui->label_gpio->setText("寄存器值："+gpio->toString());
    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
        if (   rs232 ->myCom && rs232 ->myCom ->isOpen())
        {
            ui->pushButton_read->setEnabled(true);
            ui->pushButton_save->setEnabled(true);
        }
        else
        {
            ui->pushButton_read->setEnabled(false);
            ui->pushButton_save->setEnabled(false);
        }
    }
}

void Widget_GPIO_Input::on_pushButton_save_clicked()
{
    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
       QString save_str= rs232->set_gpio(gpio_id, _gpio.toString());
        //ui->label_data->setText("写入："+save_str);

        GPIO * gpio = new GPIO;
        gpio->remote_id  = _gpio.remote_id ;
        gpio->remote_bit  = _gpio.remote_bit;
        gpio->flip  = _gpio.flip;
        gpio-> mode_input  = 1;//_gpio.mode_input;
        gpio-> level  = _gpio.level;
        gpio-> on  = _gpio.on;

        GpioSetting::gpio[com_name][gpio_id] = gpio;

      //  mHelper::ShowMessageBoxInfo("写入成功："+save_str);

        if (save_str.length() >0)
            mHelper::ShowMessageBoxInfo("写入成功");
        else
            mHelper::ShowMessageBoxInfo("写入失败");
    }
}


void Widget_GPIO_Input::on_pushButton_read_clicked()
{
    rs232com* rs232 = com_manager::instance()->get_com(com_name);
    if (rs232)
    {
          rs232->query_gpio(gpio_id);
            emit changePage();
    }
}
